import { service } from './request';
import { config } from './config';
const { default_headers } = config;

// 请求时去除为空等类型的参数
function removeEmptyValues(obj:any) {
	Object.keys(obj).forEach(key => {
		if ([null, '', undefined].includes(obj[key])) {
			delete obj[key];
		}
	});
	return obj;
}

const request = (option: any) => {
	const { url, method, params, data, headersType, responseType, ...config } = option
	if (params) {
		removeEmptyValues(params)
	}
	return service({
		url: url,
		method,
		params,
		data,
		...config,
		responseType: responseType,
		headers: {
			'Content-Type': headersType || default_headers
		}
	})
}
export default {
	get: async <T = any>(option: any) => {
		const res = await request({ method: 'GET', ...option })
		return res?.data as unknown as T
	},
	get1: async <T = any>(option: any) => {
		const res = await request({ method: 'GET', ...option })
		return res as unknown as T
	},
	post: async <T = any>(option: any) => {
		const res = await request({ method: 'POST', ...option })
		return res?.data as unknown as T
	},
	post1: async <T = any>(option: any) => {
		const res = await request({ method: 'POST', ...option })
		return res as unknown as T
	},
	postOriginal: async (option: any) => {
		const res = await request({ method: 'POST', ...option })
		return res
	},
	delete: async <T = any>(option: any) => {
		const res = await request({ method: 'DELETE', ...option })
		return res?.data as unknown as T
	},
	delete1: async <T = any>(option: any) => {
		const res = await request({ method: 'DELETE', ...option })
		return res as unknown as T
	},
	put: async <T = any>(option: any) => {
		const res = await request({ method: 'PUT', ...option })
		return res?.data as unknown as T
	},
	put1: async <T = any>(option: any) => {
		const res = await request({ method: 'PUT', ...option })
		return res as unknown as T
	},
	download: async <T = any>(option: any) => {
		const res = await request({ method: 'GET', responseType: 'blob', ...option })
		return res as unknown as Promise<T>
	},
	upload: async <T = any>(option: any) => {
		option.headersType = 'multipart/form-data'
		const res = await request({ method: 'POST', ...option })
		return res as unknown as Promise<T>
	},
	postForm: async <T = any>(option: any) => {
		option.headersType = 'multipart/form-data'
		const res = await request({ method: 'POST', ...option })
		return res as unknown as T
	},
	putForm: async <T = any>(option: any) => {
		option.headersType = 'multipart/form-data'
		const res = await request({ method: 'PUT', ...option })
		return res as unknown as T
	},
}
